$(function () {
  // 先移除原有的  token
  localStorage.removeItem("x-token");
  let form = layui.form;
  let layer = layui.layer;
  $(".layui-form").submit((e) => {
    // 获取 input 的 value值
    let login_name = $('input[name="username"]').val().trim();
    let password = $('input[name="password"]').val().trim();
    // 阻止默认行为
    e.preventDefault();
    // 发起请求
    axios({
      method: "post",
      url: "/index/login",
      // 请求头指定的 token 就像xxx去洗脚 不带手牌人家不认识你不让进
      headers: {
        token:
          "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaW5mbyI6eyJpZCI6MTM2LCJ1c2VybmFtZSI6IjExMSIsIm1vYmlsZSI6IjE4ODY4ODE2MTg1Iiwic2V4IjowLCJwYXNzd29yZCI6IiIsImljb24iOiJ1cGxvYWQvaW1hZ2VzLzIwMjIwNzExLzE2NTc1NDM0MzA2MjYuanBnIiwibm90ZXMiOiLlsLHmmK_niZvpgLznmoTnrqHnkIblkZgiLCJiaXJ0aGRheSI6IjIwMDAtMTEtMTIiLCJhZGRyZXNzIjoi5rKz5YyX55yBIOWUkOWxseW4giDot6_ljZfljLoiLCJkZWZhdWx0X2RhdGEiOiIxIn0sImlhdCI6MTY1NzU4Mzc5OX0.FCeSpLd_25dwL7s0m8mcPVZrXQPHO2VOu7IZHSshdG4",
      },
      data: {
        login_name,
        password,
      },
    }).then((res) => {
      console.log(res);
      // 判断是否成功
      if (res.status !== 200) return false;
      // 判断账户 密码是否正确
      if (
        res.data.errmsg === "账号不正确" ||
        res.data.errmsg === "密码不正确"
      ) {
        return layer.msg(res.data.errmsg);
      }
      layer.msg("账号密码正确,登陆成功");
      // 将 value 存储到key字段
      localStorage.setItem("x-token", res.data.data.token);
      // 定时器
      setTimeout(() => {
        location.href = "./index.html";
      }, 500);
    });
  });
});
